package com.example.demo.entity.config;

import com.example.demo.common.Result;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Data
@Component
@ConfigurationProperties(prefix = "rsa")
public class RsaKey {
    private String algorithm;
    private String privateKey;
    private String publicKey;

    /*
     * 获取密钥对
     **/
    public Result getKey() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
        keyGen.initialize(2048);

        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey privateKey = pair.getPrivate();
        PublicKey publicKey = pair.getPublic();

        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        Result res = new Result();
        res.ok();
        res.put("privateKey", privateKeyString);
        res.put("publicKey", publicKeyString);
        return res;
    }

    /*
     * 加密数据
     **/
    public String encrypt(String data) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(spec));

        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
    }

    /*
     * 解密数据
     **/
    public String decrypt(String data) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(spec));

        return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
    }
}
